/*
* 设备巡检任务列表
* */

import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';


class EquipmentTasks extends StatefulWidget {
  @override
  _EquipmentTasksState createState() => _EquipmentTasksState();
}

class _EquipmentTasksState extends State<EquipmentTasks> with SingleTickerProviderStateMixin {

  EasyRefreshController _controller = EasyRefreshController();
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;
  @override
  void initState() {
    super.initState();
    this.getEquipmentTask();
    bus.on('refreshEquipmentTask', (arg) {
      page = 1;
      this.getEquipmentTask();
    });
  }
  getEquipmentTask() async {
    var pass = {
      'projectSectionId': GlobalConfig.selectFactory.tag,
      'page': page,
      'limit': pageSize,
    };
    var result = await getEquipmentList(pass);
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null&&result['hasError']==null) {
      if (result['results'].length == 0) {
        _controller.finishLoad(success: true, noMore: true);
      } else {
        dataSource.addAll(result['results']);
      }
    }else{
      _controller.finishLoad(success: true);
    }
    this.setState(() {

    });
  }
  @override
  void dispose() {
    _controller.dispose();
    bus.off('refreshEquipmentTask');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('设备巡检'),

        ),
      body: Container(
        color: Styles.MainBackgroundColor,
        padding:
        EdgeInsets.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        child: NotificationListener(
          onNotification: (_) {
            FocusScope.of(context).requestFocus(new FocusNode());
            return false;
          },
          child: this.dataSource.length > 0
              ? EasyRefresh.custom(
              shrinkWrap: true,
              firstRefresh: false,
              controller: _controller,
              header: MaterialHeader(),
              footer: ClassicalFooter(
                  loadingText: '加载中',
                  loadText: '上拉加载',
                  noMoreText: '没有更多数据',
                  loadedText: '加载完成',
                  infoText: '更新于 %T',
                  textColor: Styles.NoMoreColor,
                  showInfo: false),
              emptyWidget: (dataSource.length == 0 && !firstLoad)
                  ? Center(
                child: Image(
                  image: AssetImage('assets/images/no_data.png'),
                  width: 128,
                  height: 150,
                ),
              )
                  : null,
              onRefresh: () async {
                _controller.finishLoad(success: true, noMore: false);
                if (mounted) {
                  page = 1;
                  this.getEquipmentTask();
                }
              },
              onLoad: () async {
                await Future.delayed(Duration(seconds: 2), () {
                  if (mounted) {
                    page++;
                    this.getEquipmentTask();
                  }
                });
              },
              slivers: <Widget>[
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                        (context, index) {
                      return GestureDetector(
                        onTap: () {
                          Get.toNamed(
                              RouteConfig.equipmentInspection,arguments: this.dataSource[index]);
                        },
                        child: Container(
                          color: Colors.white,
                          margin: EdgeInsets.fromLTRB(
                              0, Styles.spacing8, 0, 0),
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing12,
                              Styles.spacing8,
                              Styles.spacing12,
                              Styles.spacing8),
                          child: Row(
                            crossAxisAlignment:
                            CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                  child: Container(
                                    padding: EdgeInsets.fromLTRB(
                                        Styles.spacing12, 0, 0, 0),
                                    child: Column(
                                      crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisAlignment:
                                          MainAxisAlignment
                                              .spaceBetween,
                                          crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                          children: [
                                            Expanded(
                                              child: Container(
                                                child: Text(
                                                  this.dataSource[index]['planName']!=null?this.dataSource[index]['planName']:'--',
                                                  style: TextStyle(
                                                      color: Styles
                                                          .DetailColor,
                                                      fontSize: Styles
                                                          .NormalFont),
                                                ),
                                              ),
                                            ),

                                            !Utils.differentTime(this.dataSource[index]['planStartTimeStr'], Utils.timeUtil(DateTime.now().toIso8601String()))&&Utils.differentTime(this.dataSource[index]['planEndTimeStr'], Utils.timeUtil(DateTime.now().toIso8601String()))&&(this.dataSource[index]['lastCheckRecord']['operatorTime']==null||Utils.differentTime(Utils.timeUtil(DateTime.now().toIso8601String()),this.dataSource[index]['lastCheckRecord']['operatorTimeStr']))&&this.dataSource[index]['planStatusName']!='已巡检'
                                                ? Container(
                                              padding: EdgeInsets
                                                  .fromLTRB(
                                                  Styles
                                                      .spacing8,
                                                  0,
                                                  Styles
                                                      .spacing8,
                                                  0),
                                              decoration:
                                              BoxDecoration(
                                                color:
                                                Styles.RedColor,
                                              ),
                                              child: Text(
                                                '今日需检查',
                                                style: TextStyle(
                                                    color: Styles
                                                        .ShareWhite,
                                                    fontSize: Styles
                                                        .NormalFont),
                                              ),
                                            )
                                                : Container()
                                          ],
                                        ),
                                        Container(
                                          padding: EdgeInsets.fromLTRB(
                                              0, Styles.spacing4, 0, 0),
                                          child: Text(
                                            '最后检查时间：${this.dataSource[index]['lastCheckRecord']['operatorTimeStr']}',
                                            style: TextStyle(
                                                color: Styles.DetailColor,
                                                fontSize:
                                                Styles.NormalFont),
                                          ),
                                        ),
                                        Container(
                                          padding: EdgeInsets.fromLTRB(
                                              0, Styles.spacing4, 0, 0),
                                          child: Text(
                                            '最后检查人：${this.dataSource[index]['lastCheckRecord']['operatorName']!=null?this.dataSource[index]['lastCheckRecord']['operatorName']:'--'}',
                                            style: TextStyle(
                                                color: Styles.DetailColor,
                                                fontSize:
                                                Styles.NormalFont),
                                          ),
                                        ),
                                        Row(
                                          mainAxisAlignment:
                                          MainAxisAlignment
                                              .spaceBetween,
                                          children: [
                                            Container(
                                              padding:
                                              EdgeInsets.fromLTRB(
                                                  0,
                                                  Styles.spacing4,
                                                  0,
                                                  0),
                                              child: Text(
                                                '隐患共${this.dataSource[index]['infoQty'].toString()}个',
                                                style: TextStyle(
                                                    color: Styles
                                                        .DetailColor,
                                                    fontSize: Styles
                                                        .NormalFont),
                                              ),
                                            ),
                                            Container(
                                              padding:
                                              EdgeInsets.fromLTRB(
                                                  0,
                                                  Styles.spacing4,
                                                  0,
                                                  0),
                                              child: Text(
                                                this.dataSource[index]['planStatusName'],
                                                style: TextStyle(
                                                    color:this.dataSource[index]['planStatusName']=='未巡检'?Styles
                                                        .RedColor:(this.dataSource[index]['planStatusName']=='巡检中'?Styles
                                                        .OrangeColor:Styles
                                                        .HomeGreenCard),
                                                    fontSize: Styles
                                                        .NormalFont),
                                              ),
                                            ),

                                          ],
                                        )
                                      ],
                                    ),
                                  ))
                            ],
                          ),
                        ),
                      );
                    },
                    childCount: dataSource.length,
                  ),
                ),
              ])
              : firstLoad
              ? Center(
            child: CircularProgressIndicator(),
          )
              : Center(
            child: Image(
              image: AssetImage('assets/images/no_data.png'),
              width: 128,
              height: 150,
            ),
          ),
        ),
      ),
    );
  }
}
